package com.itdianzi.controller.enhancer;

import com.itdianzi.domain.system.SysLog;
import com.itdianzi.domain.system.User;
import com.itdianzi.service.system.SysLogService;
import org.apache.http.HttpRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Component//组件，不属于web service dao 任何一个
@Aspect//表示当前类是一个切面类  切面=切点+增强
public class SysLogEnhancer {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;

    @Around("execution(* com.itdianzi.controller.*.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {//增强


        //创建日志对象
        SysLog sysLog = new SysLog();

        sysLog.setTime(new Date());//操作的时间
        sysLog.setIp(request.getLocalAddr());//获取远程主机的IP地址

        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser != null) {

        sysLog.setCompanyId(loginUser.getCompanyId());//日志所属的企业
        sysLog.setCompanyName(loginUser.getCompanyName());//日志所属的企业名称
        sysLog.setUserName(loginUser.getUserName());//操作人

        }

        //增强  切点=需要被增强的方法（有方法名称）
        //获得方法签名对象  含有方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        //方法对象
        Method method = methodSignature.getMethod();
        sysLog.setMethod(method.getName());//操作的方法（英文）


        //判断是否有注解
        boolean flag = method.isAnnotationPresent(RequestMapping.class);
        if (flag) {//true 当前方法上有RequestMapping注解
            //获取注解对象
            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
            String name = requestMapping.name();
            sysLog.setAction(name);//操作的方法（中文）

        }

        if (!"before".equals(method.getName())) {
            //记录日志即可  调用dao方法 保存
            sysLogService.save(sysLog);
        }

        Object proceed = joinPoint.proceed();//放行语句
        return proceed;
    }
}
